import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
import joblib

# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target

# 数据分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 模型选择
model = SVC(kernel='linear', C=1.0)  # 线性核函数

# 模型训练
model.fit(X_train, y_train)

# 模型评估
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"准确率: {accuracy}")

# 保存模型
joblib_file = "svm_iris_model.pkl"
joblib.dump(model, joblib_file)
print(f"模型已保存到 {joblib_file}")

# 加载模型
loaded_model = joblib.load(joblib_file)

# 进行预测
new_data = np.array([[5.0, 3.6, 1.4, 0.2]])
prediction = loaded_model.predict(new_data)
print(f"预测结果: {iris.target_names[prediction[0]]}")
